﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using QuantBox;
using Skyline;
using SmartQuant;

namespace SgdDemo
{
    public class DemoScenario : Scenario
    {
        private void UpdateInstrument()
        {
            var list = new List<Instrument>();
            //更新上市的期货和期权合约
            list.AddRange(InstrumentManager.GetLiveFutures(DateTime.Today));
            //list.AddRange(InstrumentManager.GetLiveFutureOptions(DateTime.Today));
            if (list.Count > 0)
            {
                InstrumentManager.Clear();
                foreach (var item in list)
                {
                    if (Regex.IsMatch(item.Symbol, @"[a-zA-Z]+[89]+"))
                    {
                        continue;
                    }
                    InstrumentManager.Add(item);
                }
                InstrumentManager.Server.Flush();
            }
        }

        public DemoScenario(Framework framework) : base(framework)
        {
        }

        public override void Run()
        {
            StrategyManager.Mode = StrategyMode.Live;
            InstrumentManager.Load();
            if (InstrumentManager.Instruments.Count == 0)
            {
                UpdateInstrument();
            }
            
            strategy = new Strategy(framework, "SgdSubTest");

            var strategy1 = new TradingTestStrategy(framework, "test");
            strategy.AddStrategy(strategy1);
            
            var execProvider = ProviderManager.NewSgd("SgdSim", "sgdSub2", "sgdSub1");
            execProvider.AutoConnectUseTradingCalendar = false;
            var dataProvider = ProviderManager.NewCtpData("SimNow724", "008112", "f8");
            dataProvider.AutoConnectUseTradingCalendar = false;

            foreach (var instrument in InstrumentManager.Instruments)
            {
                if (instrument.Symbol == "ni2106")
                {
                    instrument.DataProvider = dataProvider;
                    instrument.ExecutionProvider = execProvider;
                    strategy1.AddInstrument(instrument);
                    break;
                }
            }

            var server = new StrategyServer(this).Init(@"c:\work\data\temp\SgdSubTest.db");

            if (OpenQuantOutside.RunInOpenQuant)
            {
                StartLive();
            }
            else
            {
                framework.StrategyManager.StartStrategy(strategy, StrategyMode.Live);
                CommandLineApp.Run();
                foreach (var instrument in strategy.Instruments)
                {
                    instrument.ExecutionProvider?.Disconnect();
                }
                framework.StrategyManager.Stop();
                framework.EventManager.Stop();
            }
            server.Release();
        }

    }
}